/*
 * @(#)CheckController.java $version 2013. 9. 3.
 *
 */

package com.pace.gonu.api;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pace.gonu.constants.EndType;
import com.pace.gonu.constants.Status;
import com.pace.gonu.model.chnl.PlayChannel;
import com.pace.gonu.model.status.PlayStatus;
import com.pace.gonu.play.PlayService;

/**
 * @author pace
 */
@Controller
@RequestMapping(value = "/gonu/play/api")
public class CheckController {
	@Autowired
	private PlayService playService;
	@Autowired
	private CheckService checkService;

	@RequestMapping(value = "/check.json", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap check(int chnlNumber) {
		ModelMap mm = new ModelMap();
		if (checkService.check(chnlNumber)) {
			mm.addAttribute("message", "ok");
		}
		return mm;
	}

	@RequestMapping(value = "/playCheck.json", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap playCheck(HttpSession session, int chnlNumber) {
		ModelMap mm = new ModelMap();
		String order = (String)session.getAttribute("ORDER");
		String result = checkService.playCheck(chnlNumber, order);
		mm.addAttribute("message", result);
		if (StringUtils.equals(result, "ok")) {
			PlayStatus playStatus = playService.getChannel(chnlNumber).getPlayStatusObject();
			mm.addAttribute("playStatus", playStatus);
			CollectionUtils.isEmpty(playStatus.getMoveRocks());
			if (playStatus.getStatusType().equals(Status.CHARM.toString())) {
				mm.addAttribute("alarm", "참!!\n상대방의 말을 제거하세요");
			} else if (playStatus.getStatusType().equals(Status.CHARMINMOVE.toString())) {
				mm.addAttribute("alarm", "당신차례입니다.\n상대방의 말을 제거하세요");
			} else if (playStatus.getStatusType().equals(Status.MOVE.toString())) {
				mm.addAttribute("alarm", "당신차례입니다.\n돌을 움직여주세요");
			} else {
				mm.addAttribute("alarm", "당신차례입니다.\n돌을 놓아주세요");
			}

		} else if (StringUtils.equals(result, "end")) {
			PlayChannel playChannel = playService.getChannel(chnlNumber);
			mm.addAttribute("playStatus", playChannel.getPlayStatusObject());
			if (EndType.TIMEOUT.equals(playChannel.getEndTypeObject())) {
				mm.addAttribute("alarm", "시간초과을 초과하였습니다.\n" + playChannel.getWinner().toString() + "가 이겼습니다.");
			} else {
				mm.addAttribute("alarm", "게임이 끝났습니다.\n" + playChannel.getWinner().toString() + "가 이겼습니다.");
			}

			mm.addAttribute("isPVC", playService.getChannel(chnlNumber).isPVC());
		}

		return mm;
	}
}
